package com.jaychen.eureka.invoker;

import com.jaychen.eureka.domain.InstanceInfo;
import com.jaychen.eureka.domain.Lease;
import com.jaychen.eureka.registry.DefaultInstanceRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author Jay Chen
 * @Date 2020-10-22 00:40
 * @Version 1.0
 */
@RestController
@RequestMapping("/eureka")
public class HttpInvokerHandler {

    @Autowired
    private DefaultInstanceRegistry defaultInstanceRegistry;

    /**
     * 注册心跳
     *
     * @param appName            服务名称
     * @param port               端口
     * @param instanceId         服务唯一标识id MD5（服务器ip地址 + 端口 + 服务名称）
     * @param address            服务器地址
     * @param lastDirtyTimestamp 最后心跳时间
     */
    @PostMapping("/heartBeat/{appName}/{port}/{instanceId}/{address}/{lastDirtyTimestamp}")
    public void heartBeat(@PathVariable("appName") String appName,
                          @PathVariable("port") String port,
                          @PathVariable("instanceId") String instanceId,
                          @PathVariable("address") String address,
                          @PathVariable("lastDirtyTimestamp") Long lastDirtyTimestamp) {
        InstanceInfo instanceInfo = new InstanceInfo();
        instanceInfo.setAddress(address);
        instanceInfo.setAppName(appName);
        instanceInfo.setInstanceId(instanceId);
        instanceInfo.setPort(port);
        defaultInstanceRegistry.register(instanceInfo, lastDirtyTimestamp);
    }

    /**
     * 获取注册列表
     *
     * @return 注册列表
     */
    @GetMapping("/getRegistryList")
    public Map<String, Map<String, Lease<InstanceInfo>>> getRegistryList() {
        return defaultInstanceRegistry.getRegistryList();
    }

}
